package xhwl.hmo.mall.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;
import rx.functions.Action1;
import xhwl.hmo.mall.BaseFragmentActivity;
import xhwl.hmo.mall.IntentConstants;
import xhwl.hmo.mall.MyApp;
import xhwl.hmo.mall.R;
import xhwl.hmo.mall.event.UpgradeEvent;
import xhwl.hmo.mall.http.api.UpdateLoginInfoApi;
import xhwl.hmo.mall.http.bean.resp.ResponseError;
import xhwl.hmo.mall.receiver.bean.PushType;
import xhwl.hmo.mall.ui.fragment.FindFragment;
import xhwl.hmo.mall.ui.fragment.HomeFragment;
import xhwl.hmo.mall.ui.fragment.MineFragment;
import xhwl.hmo.mall.utils.AppUtil;
import xhwl.hmo.mall.utils.BaiduLocateMgr;
import xhwl.hmo.mall.utils.PermisionUtils;
import xhwl.hmo.mall.utils.SpUtil;
import xhwl.hmo.mall.utils.StringUtil;
import xhwl.hmo.mall.utils.UpgradeMgr;
import xhwl.retrofitrx.BaseApi;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

public class MainActivity extends BaseFragmentActivity implements View.OnClickListener {
    private static final String TAG = MainActivity.class.getSimpleName();
    private FrameLayout tabcontent;
    private LinearLayout llayoutTabHome,llayoutTabFind,llayoutTabMine;

    private ImageView ivTabHome,ivTabMine,ivTabFind;
    private TextView tvTabHome,tvTabMine,tvFind;

//    public static MainActivity instance;
    private HomeFragment homeFragment;
    private FindFragment findFragment;
    private MineFragment mineFragment;

    private Fragment fragmentByTag;
    private LinearLayout main;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        manager = getSupportFragmentManager();
//        DimenUtil.setStatusBar(this);
        setContentView(R.layout.activity_main);
//        instance = this;
    }

    @Override
    public void initViews() {
        main = (LinearLayout) findViewById(R.id.main);
        tabcontent = (FrameLayout) findViewById(R.id.tabcontent);
        ivTabHome = (ImageView) findViewById(R.id.ivTabSaleCard);
        tvTabHome = (TextView) findViewById(R.id.tvTabSaleCard);
        llayoutTabHome = (LinearLayout) findViewById(R.id.llayoutTabHome);
        ivTabMine = (ImageView) findViewById(R.id.ivTabMine);
        tvTabMine = (TextView) findViewById(R.id.tvMine);
        llayoutTabMine = (LinearLayout) findViewById(R.id.llayoutTabMine);


        ivTabFind = (ImageView) findViewById(R.id.ivTabFind);
        tvFind = (TextView) findViewById(R.id.tvFind);
        llayoutTabFind = (LinearLayout) findViewById(R.id.llayoutTabFind);
    }

    @Override
    protected void processOper() {
        super.processOper();

        requestPermission();
    }

    @Override
    public void initListener() {
        llayoutTabHome.setOnClickListener(this);
        llayoutTabMine.setOnClickListener(this);
        llayoutTabFind.setOnClickListener(this);
        llayoutTabHome.performClick();
    }

    @Override
    public void loadData() {
        Bundle bundleExtra = getIntent().getBundleExtra(IntentConstants.EXTRA_PUSH_BUNDLE);
        if(bundleExtra!=null){
            String pushType = bundleExtra.getString(IntentConstants.EXTRA_PUSH_TYPE);
            if(StringUtil.isEmpty(pushType))
                return;
            if(PushType.CERTIFICATE.equals(pushType)){
                if(!AppUtil.isLogin()){
                    AppUtil.startLoginActivity(mContext);
                }
                else
                {
                    Intent i = new Intent(mContext, PersonListActivity.class);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
                    mContext.startActivity(i);
                }
            }else if(PushType.CONSIGN.equals(pushType)){
                if(!AppUtil.isLogin()){
                    AppUtil.startLoginActivity(mContext);
                }
                else
                {
                    Intent i = new Intent(mContext, InfoOrderActivity.class);
                    i.putExtra(InfoOrderActivity.EXTRA_ORDER_ID,bundleExtra.getString(IntentConstants.EXTRA_PUSH_ORDER_ID));
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
                    mContext.startActivity(i);
                }
            }
        }
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llayoutTabHome:
                changeFragment(0);
                break;
            case R.id.llayoutTabFind:
                changeFragment(1);
                break;
            case R.id.llayoutTabMine:
                changeFragment(2);
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // 判断是否接受通知
        boolean isPushOn = SpUtil.getBoolean(SpUtil.PUSH_ON,true);
        if (isPushOn) {
            JPushInterface.resumePush(getApplicationContext());
        } else {
            JPushInterface.stopPush(getApplicationContext());
        }
    }

    public void changeFragment(int tabpage) {
        transaction = manager.beginTransaction();
        resetTabView();
        hide();
        switch (tabpage) {
            case 0:
//                if (saleCardFragment == null) {
                homeFragment = null;
                homeFragment = new HomeFragment();
                transaction.add(R.id.tabcontent, homeFragment, "HomeFragment");
//                } else {
//                    transaction.show(saleCardFragment);
//                }
                ivTabHome.setImageDrawable(getResources().getDrawable(R.drawable.icon_store_select));
                tvTabHome.setTextColor(getResources().getColor(R.color.main_tab_text_selected));
                tvTabHome.getPaint().setFakeBoldText(true);
                break;

            case 1:
                findFragment = null;
                findFragment = new FindFragment();
                transaction.add(R.id.tabcontent, findFragment);
                ivTabFind.setImageDrawable(getResources().getDrawable(R.drawable.icon_discover_select));
                tvFind.setTextColor(getResources().getColor(R.color.main_tab_text_selected));
                tvFind.getPaint().setFakeBoldText(true);
                break;

            case 2:
                //有时网络请求失败无法显示页面信息,只能每次都重新加载新的fragment
//                if (mineFragment == null) {
                mineFragment = null;
                mineFragment = new MineFragment();
                transaction.add(R.id.tabcontent, mineFragment);
//                } else {
//                    transaction.show(mineFragment);
//                }
                ivTabMine.setImageDrawable(getResources().getDrawable(R.drawable.icon_mine_select));
                tvTabMine.setTextColor(getResources().getColor(R.color.main_tab_text_selected));
                tvTabMine.getPaint().setFakeBoldText(true);
                break;
        }
        transaction.commitAllowingStateLoss();
    }

    private void hide() {
        if (homeFragment != null) {
            transaction.hide(homeFragment);
        }
        if (findFragment != null) {
            transaction.hide(findFragment);
        }
        if (mineFragment != null) {
            transaction.hide(mineFragment);
        }
    }

    public void resetTabView() {
        ivTabHome.setImageDrawable(getResources().getDrawable(R.drawable.icon_store));
        tvTabHome.setTextColor(getResources().getColor(R.color.main_tab_text_normal));
        tvTabHome.getPaint().setFakeBoldText(false);
        ivTabFind.setImageDrawable(getResources().getDrawable(R.drawable.icon_discover));
        tvFind.setTextColor(getResources().getColor(R.color.main_tab_text_normal));
        tvFind.getPaint().setFakeBoldText(false);
        ivTabMine.setImageDrawable(getResources().getDrawable(R.drawable.icon_mine));
        tvTabMine.setTextColor(getResources().getColor(R.color.main_tab_text_normal));
        tvTabMine.getPaint().setFakeBoldText(false);
    }


    // 用来计算返回键的点击间隔时间
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void onEvent(Object obj) {
        if (obj instanceof UpgradeEvent) {
            UpgradeEvent event = (UpgradeEvent) obj;
            if (event.isDownloadComplete()) {
                new UpgradeMgr().checkVersion(this);
            } else if (event.isStartDownload()) {
//                ToastUtil.showToast(this, "开始下载...");
            } else if (event.isNewest()) {
//                ToastUtil.showToast(this, "当前已是最新版本");
            } else if (event.isDownloading()) {
//                ToastUtil.showToast(this, "下载中...");
            }
        }
    }

    private void requestPermission() {
        new RxPermissions(this).requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA)
                .subscribe(new Action1<Permission>() {
                    @Override
                    public void call(Permission permission) {
                        if (Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permission.name)) {
                            if (permission.granted) {
                                new UpgradeMgr().checkVersion(MainActivity.this);
                            } else {
                                Log.e(TAG,
                                        "用户拒绝开启存储");
                                PermisionUtils.dialog(MainActivity.this, "读取手机存储");
                            }
                            updateDeviceInfo();
                        } else if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permission.name)) {
                            if (permission.granted) {
                                BaiduLocateMgr locateMgr = new BaiduLocateMgr(MainActivity.this, new BaiduLocateMgr.Callback() {
                                    @Override
                                    public void locateSuccess(double lat, double lng, String address) {
                                        MyApp.lat = lat + "";
                                        MyApp.lng = lng + "";
                                    }
                                });
                                locateMgr.startLocate();
                            } else {
                                Log.e(TAG,
                                        "用户拒绝开启定位");
                            }
                        }
                    }
                });
    }
    private void updateDeviceInfo(){
        if(!AppUtil.isLogin()){
            return;
        }
//        boolean hasUpdateDeviceInfo= SpUtil.getBoolean(SpUtil.HAS_UPDATE_DEVICE_INFO,false);
//        if(!hasUpdateDeviceInfo){
            String linkMobile=SpUtil.getString(SpUtil.MEMBER_MOBILE,"");
            String phoneId= AppUtil.getImei(mContext);
            String phoneUnion=android.os.Build.MODEL;
            String versonName=AppUtil.getVersionName(mContext);
            BaseApi api=new UpdateLoginInfoApi(linkMobile,phoneId,phoneUnion,versonName);
            HttpManager.getInstance().dealHttp(this,api,new OnNextListener<ResponseError>(){
                @Override
                public void onNext(ResponseError error) {
                    if(error!=null&&error.isOk()){
                        SpUtil.putBoolean(SpUtil.HAS_UPDATE_DEVICE_INFO,true);
                    }
                }
            });
//        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);

        if (null != PermisionUtils.alertDialog)
            PermisionUtils.alertDialog.dismiss();
//        if (null != instance)
//            instance.finish();
    }

}
